﻿<%@ WebHandler Language="C#" Class="App_Game" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
public class App_Game : IHttpHandler, IRequiresSessionState
{

    string msg = string.Empty;
    private const double EARTH_RADIUS = 6378.137;

    private double p_longitude = 103.984952;
    private double p_latituede = 1.351611;
    readonly WinLog WinLog = new WinLog();
    readonly Users Users = new Users();
    public void ProcessRequest(HttpContext context)
    {
        CurrentContext = context;
        try
        {
            string action = context.Request.QueryString["action"].ToString();
           
            string udid = string.Empty;
          
            //string realname = string.Empty;        
            string token = string.Empty;
            string month = string.Empty;
            string butterflys = string.Empty;
            string latitude = string.Empty;
            string longitude = string.Empty;
            udid = GetQuery("udid");
            
            //PC端使用参数
           
            
            switch (action.ToLower())
            {
                    
                case "checkin":
                    token = GetQuery("token");
                    longitude = GetQuery("longitude");
                    latitude = GetQuery("latitude"); 
                    CheckIn(token, udid,longitude,latitude);
                    break;
                case "butterflychange":
                    token = GetQuery("token");
                    butterflys = GetQuery("butterflys");
                    ButterFlyChange(token, butterflys, udid);
                    break;
                case "butterflyleft":
                    token = GetQuery("token");
                    longitude = GetQuery("longitude");
                    latitude = GetQuery("latitude");
                    GetButterFlys(token,  udid,longitude,latitude);
                    break;

                case "pointranking":
                    token = GetQuery("token");

                    GetRanking(token, udid);
                    break;
                    
                case "getrankwithparas":
                    token = GetQuery("token");
                    month = GetQuery("month");
                    GetRankByMonthAndToken(month,token);
                    break;

                case "getrankwithparasformart":
                    token = GetQuery("token");
                    month = GetQuery("month");
                    GetRankByMonthAndTokenFormart(month, token);
                    break;

                case "invateget":
                    token = GetQuery("token");
                    InvateGet(token);
                    break;   

                case "personrank":
                    token = GetQuery("token");
                    GetPersonalPoint(token);
                    break;

                case "rankbymonth":
                    month = GetQuery("month");
                    GetRankByMonth(month);
                    break;
               
            }
        }
        catch (Exception err)
        {
            msg = "{\"result\":\"error\",\"msg\":\"" + err.Message + "\"}";
        }
        finally
        {
            context.Response.Write(msg);
        }
    }
    public HttpContext CurrentContext;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    public string GetQuery(string name)
    {
        string res = string.Empty;
        if (CurrentContext.Request.QueryString[name] != null)
            res = CurrentContext.Request.QueryString[name].ToString();
        return res;
    }

    public void InvateGet(string token)
    {
        if (string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {

            msg = "{\"result\":\"success\"}";
            if (WinLog.CountByToday(token, "邀请好友") < 4)
                WinLog.Create(WinLog.GAME_INVITE, token, "邀请好友", "邀请好友");
            else
            {
                msg = "{\"result\":\"error\",\"msg\":\"超出范围\"}";
            }
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";
    }

    public void CheckIn(string token, string udid, string longitude, string latitude)
    {
        if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(udid) || string.IsNullOrEmpty(longitude) || string.IsNullOrEmpty(latitude))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {
            if (IsEffectiveRange(latitude,longitude))
            {
                msg = "{\"result\":\"success\"}";
                if (WinLog.CountByToday(token, "签到积分") < 10)
                    WinLog.Create(WinLog.GAME_CHECKIN, token, "签到积分", "签到积分");
            }
            else
            {
                msg = "{\"result\":\"error\",\"msg\":\"超出范围\"}";
            }
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";
            
    }

    public void ButterFlyChange(string token, string butterflys, string udid)
    {
        if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(udid) || string.IsNullOrEmpty(butterflys))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {
            
            if(butterflys.Split(new string[]{","},StringSplitOptions.None).Length!=5)
            {
              msg = "{\"result\":\"error\",\"msg\":\"必须有5只蝴蝶才能兑换\"}";
              if (WinLog.CountByToday(token, "兑换蝴蝶积分") < 100)
                  WinLog.Create(WinLog.GAME_BTTTERFLY, token, "兑换蝴蝶积分", "兑换蝴蝶积分");
            }
            else
              msg = "{\"result\":\"success\"}";
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";

    }

    public void GetButterFlys(string token, string udid, string longitude, string latitude)
    {
        if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(udid)  || string.IsNullOrEmpty(longitude) || string.IsNullOrEmpty(latitude))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {
            //**
            if (false)
            {
                msg = "{\"result\":\"error\",\"msg\":\"不在机场范围内\"}";
            }
            else
            {
                msg = "{\"result\":\"success\",\"count\":2000}";
            }
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";

    }

    public void GetRanking(string token, string udid)
    {
        
            string strWhere = string.Empty;
            if (!string.IsNullOrEmpty(token) )
                 strWhere=string.Format(" Token='{0}' ",token);
            
            System.Data.DataTable dt = WinLog.GetRanking(strWhere,10);
            msg = "{\"result\":\"success\",\"count\":" + dt.Rows.Count.ToString() + ",\"data\":[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                System.Data.DataRow dr = dt.Rows[i];
                msg += "{\"token\":\"" + dr["Token"].ToString() + "\",";
                msg += "\"place\":\"" + dr["Place"].ToString() + "\",";
                msg += "\"point\":\"" + dr["Point"].ToString() + "\",";
                msg += "\"realname\":\"" + dr["UName"].ToString() + "\"}";
                if (i < dt.Rows.Count - 1)
                    msg += ",";
            }
            msg += "]}";
        
    }

    public void GetPersonalPoint(string token)
    {
        if (!string.IsNullOrEmpty(token))
        {
            System.Text.StringBuilder rankBuilder = new System.Text.StringBuilder();
     
            rankBuilder.Append(" select ");
            rankBuilder.Append(" datepart(month,CTime) as MonthAt,sum(Point) as Point, uid, ");
            rankBuilder.Append(" (select sum(Point) from Users_WinLog uw1 where uw1.uid=uw.uid ) as TotalPoint ");
            rankBuilder.Append(" from Users_WinLog uw ");
            rankBuilder.AppendFormat(" where Token='{0}' ",token);
            rankBuilder.Append(" group by datepart(month,CTime),uid ");

            System.Data.DataTable dtRank = Gomye.DataUtility.SqlRunner.DoSqlTable(rankBuilder.ToString());
            if (dtRank.Rows.Count > 0)
            {
                msg = "{\"result\":\"success\",\"count\":" + dtRank.Rows.Count.ToString() + ",\"data\":[";
                for (int i = 0; i < dtRank.Rows.Count; i++)
                {
                    System.Data.DataRow dr = dtRank.Rows[i];
                    msg += "{\"month\":\"" + dr["MonthAt"].ToString() + "\",";
                    msg += "\"point\":\"" + dr["Point"].ToString() + "\",";
                    msg += "\"total\":\"" + dr["TotalPoint"].ToString() + "\"}";
                    if (i < dtRank.Rows.Count - 1)
                        msg += ",";
                }
                msg += "]}";
            }
            else
            {
                msg = "{\"result\":\"success\",\"count\":\"0\"}";
            }
        }
        else
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
    }

    public void GetRankByMonthAndToken(string month, string token)
    {
        if (!string.IsNullOrEmpty(month) && !string.IsNullOrEmpty(token))
        {
            System.Text.StringBuilder rankBuilder = new System.Text.StringBuilder();
            month = JSON.CoatnvertJson(month);

            rankBuilder.Append(" select Place,uid,point,Token from ( ");
            rankBuilder.Append(" select row_number() over (order by bbb.Point desc) as Place,uid,point,Token from ");
            rankBuilder.Append(" (select uid,sum(Point) as Point,(select top 1 Token from Users u where u.uid=uw.uid ) as Token ");
            rankBuilder.AppendFormat(" from users_winlog uw where datepart(month,CTime) = {0} ", month);
            rankBuilder.Append(" group by uid ");
            rankBuilder.Append(" ) as bbb ");
            rankBuilder.Append(" ) as aaa ");
            rankBuilder.AppendFormat(" where Token='{0}' ", token);
            rankBuilder.Append(" order by aaa.Point desc ");

            System.Data.DataTable dtRank = Gomye.DataUtility.SqlRunner.DoSqlTable(rankBuilder.ToString());
            if (dtRank.Rows.Count > 0)
            {
                msg = "{\"result\":\"success\",\"count\":" + dtRank.Rows.Count.ToString() + ",\"data\":[";
                for (int i = 0; i < dtRank.Rows.Count; i++)
                {
                    System.Data.DataRow dr = dtRank.Rows[i];
                    string strPointTemp = dr["Point"].ToString();
                    msg += "{\"uid\":\"" + dr["uid"].ToString() + "\",";
                    msg += "\"point\":\"" + strPointTemp + "\",";
                    msg += "\"place\":\"" + dr["Place"].ToString() + "\"}";
                    if (i < dtRank.Rows.Count - 1)
                        msg += ",";
                }
                msg += "]}";
            }
            else
            {
                msg = "{\"result\":\"success\",\"count\":\"0\"}";
            }
        }
        else
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
    }

    public void GetRankByMonthAndTokenFormart(string month, string token)
    {
        if (!string.IsNullOrEmpty(month) && !string.IsNullOrEmpty(token))
        {
            System.Text.StringBuilder rankBuilder = new System.Text.StringBuilder();
            month = JSON.CoatnvertJson(month);

            rankBuilder.Append(" select Place,uid,point,Token from ( ");
            rankBuilder.Append(" select row_number() over (order by bbb.Point desc) as Place,uid,point,Token from ");
            rankBuilder.Append(" (select uid,sum(Point) as Point,(select top 1 Token from Users u where u.uid=uw.uid ) as Token ");
            rankBuilder.AppendFormat(" from users_winlog uw where datepart(month,CTime) = {0} ", month);
            rankBuilder.Append(" group by uid ");
            rankBuilder.Append(" ) as bbb ");
            rankBuilder.Append(" ) as aaa ");
            rankBuilder.AppendFormat(" where Token='{0}' ", token);
            rankBuilder.Append(" order by aaa.Point desc ");

            System.Data.DataTable dtRank = Gomye.DataUtility.SqlRunner.DoSqlTable(rankBuilder.ToString());
            if (dtRank.Rows.Count > 0)
            {
                msg = "{\"result\":\"success\",\"count\":" + dtRank.Rows.Count.ToString() + ",\"data\":[";
                for (int i = 0; i < dtRank.Rows.Count; i++)
                {
                    System.Data.DataRow dr = dtRank.Rows[i];

                    string strPointTemp = dr["Point"].ToString();

                    int Dlength = strPointTemp.Length;
                    if (Dlength != 5)
                    {
                        if (Dlength < 5)
                        {
                            while (Dlength != 5)
                            {
                                strPointTemp = "0" + strPointTemp;
                                Dlength = strPointTemp.Length;
                            }
                        }
                    }

                    msg += "{\"uid\":\"" + dr["uid"].ToString() + "\",";
                    msg += "\"point\":\"" + strPointTemp + "\",";
                    msg += "\"place\":\"" + dr["Place"].ToString() + "\"}";
                    if (i < dtRank.Rows.Count - 1)
                        msg += ",";
                }
                msg += "]}";
            }
            else
            {
                msg = "{\"result\":\"success\",\"count\":\"0\"}";
            }
        }
        else
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
    }


        
    public void GetRankByMonth(string month)
    {
        if (!string.IsNullOrEmpty(month))
        {
            System.Text.StringBuilder rankBuilder = new System.Text.StringBuilder();
            month= JSON.CoatnvertJson(month);

            rankBuilder.Append(" select top 10 ");
            rankBuilder.Append(" datepart(month,CTime) as MonthAt,sum(Point) as Point, uid,(select top 1 UName from Users u where u.uid=uw.uid ) as UName ");
            rankBuilder.Append(" from Users_WinLog uw ");
            rankBuilder.AppendFormat(" where datepart(month,CTime)={0} ",month);
            rankBuilder.Append(" group by datepart(month,CTime),uid ");
            rankBuilder.Append(" order by point desc ");
            System.Data.DataTable dtRank = Gomye.DataUtility.SqlRunner.DoSqlTable(rankBuilder.ToString());
            if (dtRank.Rows.Count > 0)
            {
                msg = "{\"result\":\"success\",\"count\":" + dtRank.Rows.Count.ToString() + ",\"data\":[";
                for (int i = 0; i < dtRank.Rows.Count; i++)
                {
                    System.Data.DataRow dr = dtRank.Rows[i];
                    msg += "{\"month\":\"" + dr["MonthAt"].ToString() + "\",";             
                    msg += "\"point\":\"" + dr["Point"].ToString() + "\",";
                    msg += "\"realname\":\"" + dr["UName"].ToString() + "\"}";
                    if (i < dtRank.Rows.Count - 1)
                        msg += ",";
                }
                msg += "]}";
            }
            else
            {
                msg = "{\"result\":\"success\",\"count\":\"0\"}";
            }
        }
        else
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
    }

    public bool IsEffectiveRange(string lat1, string lng1)
    {
        double n_latitude;
        double n_longitude;
        double.TryParse(lat1, out n_latitude);
        double.TryParse(lng1, out n_longitude);
        double doubleDistance = GetDistance(n_latitude, n_longitude, p_latituede, p_longitude);

        if (doubleDistance < 1000)
        {
            return true;
        }
        else
        {
            return false; 
        }
    }

    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }

    public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
    {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
         Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.Round(s * 10000) / 10000;
        return s;
    }

}
